<template>
  <div class="app-container">
    <!-- 待审合同区域 -->
    <el-card shadow="hover" class="mb20 section-block">
      <h3 style="margin-bottom: 20px;">待审合同</h3>
      <!-- 查询表单 -->
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="合同号" prop="contractId" style="margin-right: 20px;">
          <el-input v-model="queryParams.contractId" placeholder="请输入合同号" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="港口名称" prop="port" style="margin-right: 20px;">
          <el-input v-model="queryParams.port" placeholder="请输入港口名称" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="货主名称" prop="owner" style="margin-right: 20px;">
          <el-input v-model="queryParams.owner" placeholder="请输入货主名称" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="合同类型" prop="contractType" style="margin-right: 20px;">
          <el-select v-model="queryParams.contractType" placeholder="请选择合同类型" clearable>
            <el-option v-for="dict in dict.type.sys_contract_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <el-row :gutter="10" class="mb8" style="margin-top: 10px;">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-check" size="mini" :disabled="multiple" @click="handleAudit" v-hasPermi="['audition:audition:add']">去审核</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['BussinessContract:contractmanadge:export']">导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <!-- 合同信息表格 -->
      <el-table v-loading="loading" :data="contractmanadgeList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="合同号" align="center" prop="contractId" />
        <el-table-column label="港口" align="center" prop="port" />
        <el-table-column label="货主" align="center" prop="owner" />
        <el-table-column label="合同类型" align="center" prop="contractType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_contract_type" :value="scope.row.contractType" />
          </template>
        </el-table-column>
        <el-table-column label="合同签订日期" align="center" prop="signDate" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.signDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="合同生效日期" align="center" prop="effectDate" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.effectDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="合同终止日期" align="center" prop="expirationDate" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.expirationDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="合同状态" align="center" prop="status">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_contract_cstatus" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="合同内容摘要" align="center" prop="contentSummary" />
        <el-table-column label="合同内容哈希值" align="center" prop="contentHash" />
        <el-table-column label="到验号" align="center" prop="uniqueCode" />
        <el-table-column label="船名" align="center" prop="shipName" />
        <el-table-column label="作废日期" align="center" prop="abolishDate" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.abolishDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="公司ID" align="center" prop="companyId" />
        <el-table-column label="货物类型" align="center" prop="cargoType" />
        <el-table-column label="合同总量" align="center" prop="volume" />
        <el-table-column label="单位" align="center" prop="unit" />
        <el-table-column label="单价" align="center" prop="price" />
        <el-table-column label="币种" align="center" prop="currency" />
        <el-table-column label="备注说明" align="center" prop="remarks" />
        <el-table-column label="合同原件" align="center" prop="contentUrl">
          <template v-slot="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleDownload(scope.row)">下载</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
        style="margin-top: 20px;"
      />
    </el-card>

    <!-- 审核记录区域 -->
    <el-card shadow="hover" class="section-block">
      <h3 style="margin-bottom: 20px;">审核记录</h3>

      <!-- 筛选表单 -->
      <el-form :model="auditQueryParams" size="small" :inline="true" label-width="100px" style="margin-bottom: 20px;">
        <el-form-item label="合同号" style="margin-right: 20px;">
          <el-input v-model="auditQueryParams.contractId" placeholder="请输入合同号" clearable />
        </el-form-item>
        <el-form-item label="港口状态" style="margin-right: 20px;">
          <el-select v-model="auditQueryParams.portApprovalStatus" placeholder="请选择港口状态" clearable>
            <el-option v-for="dict in dict.type.sys_approval_status" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="货主状态" style="margin-right: 20px;">
          <el-select v-model="auditQueryParams.ownerApprovalStatus" placeholder="请选择货主状态" clearable>
            <el-option v-for="dict in dict.type.sys_approval_status" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="getAuditList">查询</el-button>
          <el-button icon="el-icon-refresh" @click="resetAuditQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table :data="auditList" v-loading="loading">
        <el-table-column prop="contractId" label="合同号" align="center" />
        <el-table-column prop="portApprovalStatus" label="港口状态" align="center" />
        <el-table-column prop="portApprovalComments" label="港口意见" align="center" />
        <el-table-column prop="portApprovalTime" label="港口时间" align="center" />
        <el-table-column prop="ownerApprovalStatus" label="货主状态" align="center" />
        <el-table-column prop="ownerApprovalComments" label="货主意见" align="center" />
        <el-table-column prop="ownerApprovalTime" label="货主时间" align="center" />
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="auditTotal > 0"
        :total="auditTotal"
        :page.sync="auditQueryParams.pageNum"
        :limit.sync="auditQueryParams.pageSize"
        @pagination="getAuditList"
        style="margin-top: 20px;"
      />
    </el-card>

    <!-- 审核记录表单 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="合同号" prop="contractId">
          <el-input v-model="form.contractId" placeholder="请输入合同号" disabled />
        </el-form-item>
        <el-form-item label="选择身份">
          <el-radio-group v-model="selectedRole">
            <el-radio label="port">港口</el-radio>
            <el-radio label="owner">货主</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="港口审批状态" prop="portApprovalStatus" v-if="selectedRole === 'port'">
          <el-select v-model="form.portApprovalStatus" placeholder="请选择港口审批状态" clearable>
            <el-option
              v-for="dict in dict.type.sys_approval_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="港口审批意见" prop="portApprovalComments" v-if="selectedRole === 'port'">
          <el-input v-model="form.portApprovalComments" placeholder="请输入港口审批意见" />
        </el-form-item>
        <el-form-item label="货主审批状态" prop="ownerApprovalStatus" v-if="selectedRole === 'owner'">
          <el-select v-model="form.ownerApprovalStatus" placeholder="请选择货主审批状态" clearable>
            <el-option
              v-for="dict in dict.type.sys_approval_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="货主审批意见" prop="ownerApprovalComments" v-if="selectedRole === 'owner'">
          <el-input v-model="form.ownerApprovalComments" placeholder="请输入货主审批意见" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
.mb20 {
  margin-bottom: 20px;
}
.section-block {
  padding: 20px;
  background: #fafafa;
  border-radius: 6px;
}
</style>


<script>
import { listcontractmanadge, getcontractmanadge, updatecontractmanadge } from "@/api/BussinessContract/contractmanadge";
import { listAudition, addAudition, updateAudition } from "@/api/audition/audition";
import { addContract } from "@/api/fabricBussinessContract/fabricBussinessContract";

export default {
  name: "合同审批",
  dicts: ['sys_contract_cstatus', 'sys_contract_type', 'sys_port_owner', 'sys_approval_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 合同信息表格数据
      contractmanadgeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      selectedRole: 'port', // 默认选择港口
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        contractId: null,
        port: null,
        owner: null,
        contractType: null,
        signDate: null,
        effectDate: null,
        expirationDate: null,
        status: "审核中"
      },
      auditList: [],
      auditTotal: 0,
      auditQueryParams: {
        pageNum: 1,
        pageSize: 10,
        contractId: null,
        portApprovalStatus: null,
        ownerApprovalStatus: null,
      },
      // 表单参数
      form: {
        recordId: null,
        contractId: null,
        portApprovalTime:null,
        ownerApprovalTime:null,
        portApprovalStatus: null,
        ownerApprovalStatus: null,
        portApprovalComments: null,
        ownerApprovalComments: null
      },
      // 表单校验
      rules: {
        portApprovalStatus: [
          { required: true, message: "港口审批状态不能为空", trigger: "change" }
        ],
        ownerApprovalStatus: [
          { required: true, message: "货主审批状态不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getAuditList();

  },
  methods: {
    /** 查询合同信息列表 */
    getList() {
      this.loading = true;
      listcontractmanadge(this.queryParams).then(response => {
        this.contractmanadgeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    resetAuditQuery() {
      this.auditQueryParams = {
        pageNum: 1,
        pageSize: 10,
        contractId: null,
        portApprovalStatus: null,
        ownerApprovalStatus: null
      };
      this.getAuditList();
    },
    handleDownload(row){
      // var name = row.fileName;
      var url = row.contentUrl;
      this.$download.resource(url,false)
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.resetForm("form");
    },
    // 表单重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.contractId);
      this.multiple = !selection.length;
    },
    /** 去审核按钮操作 */
    handleAudit() {
      const contractId = this.ids[0];
      this.form.contractId = contractId;
      this.open = true;
      this.title = "审核合同";
    },
    /** 提交审核按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 通过验证后，提交审批记录
          this.submitRecord();  // 调用 submitRecord() 方法来处理审批记录

          // if (this.form.recordId) {
          //   updateAudition(this.form).then(response => {
          //     this.$modal.msgSuccess("修改成功");
          //     this.open = false;
          //     this.getList();
          //   });
          // } else {
          //   addAudition(this.form).then(response => {
          //     this.$modal.msgSuccess("新增成功");
          //     this.open = false;
          //     this.getList();
          //   });
          // }
          // 更新合同状态
          this.updateContractStatus();
        }
      });
    },
    /** 更新合同状态 */
    updateContractStatus() {
      const contractId = this.form.contractId;
      getcontractmanadge(contractId).then(response => {
        const contract = response.data;
        let newStatus = ""; // 新增一个变量存状态
        if (this.form.portApprovalStatus === "通过" && this.form.ownerApprovalStatus === "通过") {
          contract.status = "审核通过";
          // 调用区块链新增合同接口
          addContract(contract).then(() => {
            this.$modal.msgSuccess("合同已上链");
          });
        } else if (this.form.portApprovalStatus === "退回" || this.form.ownerApprovalStatus === "退回") {
          contract.status = "审核退回";
        }
        updatecontractmanadge(contract).then(() => {
          this.$modal.msgSuccess(`合同状态更新为${contract.status}`);
        });
      });
    },
      // 查询现有记录
      async getExistingRecord(contractId) {
        try {
          const response = await listAudition({ contractId });
          return response.data && response.data.length > 0 ? response.data[0] : null;
        } catch (error) {
          console.error("Error fetching existing record:", error);
          return null;
        }
      },
    // 提交新记录或更新现有记录
    async submitRecord() {
      const { form } = this;
      const existingRecord = await this.getExistingRecord(form.contractId);

      if (existingRecord) {
        // 如果记录存在
        if (existingRecord.portApprovalStatus && existingRecord.ownerApprovalStatus
          && existingRecord.portApprovalStatus !== "退回"
          && existingRecord.ownerApprovalStatus !== "退回") {
          // 如果记录已经完成，不允许再次提交
          this.$message.error("该合同的审批记录已完成，无法再次提交");
          return;
        }
        // 如果记录未完成，允许更新
        if (existingRecord.portApprovalStatus && form.ownerApprovalStatus) {
          // 如果港口审批状态已存在，只能更新货主审批状态
          existingRecord.ownerApprovalStatus = form.ownerApprovalStatus;
          existingRecord.ownerApprovalComments = form.ownerApprovalComments;
          existingRecord.ownerApprovalTime = new Date(); // 设置货主审批时间
        } else if (existingRecord.ownerApprovalStatus && form.portApprovalStatus) {
          // 如果货主审批状态已存在，只能更新港口审批状态
          existingRecord.portApprovalStatus = form.portApprovalStatus;
          existingRecord.portApprovalComments = form.portApprovalComments;
          existingRecord.portApprovalTime = new Date(); // 设置港口审批时间
        } else {
          // 如果记录未完成且当前用户未填写任何审批状态，不允许提交
          this.$message.error("请填写港口或货主的审批状态");
          return;
        }
        // 更新现有记录
        await updateAudition(existingRecord);
        this.$message.success("审批记录更新成功");
      } else {
        // 如果记录不存在，创建新记录
        const newRecord = {
          ...form,
          portApprovalTime: form.portApprovalStatus ? new Date() : null, // 如果港口审批状态存在，设置港口审批时间
          ownerApprovalTime: form.ownerApprovalStatus ? new Date() : null, // 如果货主审批状态存在，设置货主审批时间
        };
        await addAudition(newRecord);
        this.$message.success("审批记录创建成功");
      }
      this.open = false;
      this.getList();
    },

    getAuditList() {
      listAudition(this.auditQueryParams).then(response => {
        this.auditList = response.rows;
        this.auditTotal = response.total;
      });
    },


  }
};
</script>
